/*
 * Created on 2004-11-22
 */
package org.nanhill.support.commonfileupload;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * @author alin
 */
public class FileUploadSupport {
	// private final static Log log =
	// LogFactory.getLog(FileUploadSupport.class);

	//
	// /**
	// * TODO: need improve
	// *
	// * store the upload file to dir use the same name
	// *
	// * @param item
	// * @param dirPath
	// * @return
	// * @throws FileUploadException
	// */
	// public static File uploadFile(String locDir, String tempDir,
	// HttpServletRequest request) throws FileUploadException {
	// try {
	// DiskFileUpload fu = new DiskFileUpload();
	// // the maximum size of the upload file
	// fu.setSizeMax(25242880);
	// // the maximum size that will be stored in memory is 512kb
	// fu.setSizeThreshold(524288);
	// fu.setRepositoryPath(tempDir);
	// List fileItems = fu.parseRequest(request);
	// Iterator iter = fileItems.iterator();
	// File savedFile = null;
	// while (iter.hasNext()) {
	// FileItem item = (FileItem) iter.next();
	// // �����������ļ�������б?��Ϣ
	// if (!item.isFormField()) {
	// String name = item.getName();
	// long size = item.getSize();
	// if ((name == null || name.equals("")) && size == 0)
	// continue;
	// // ע��item.getName()
	// // �᷵�������ļ��ڿͻ��˵�����·����ƣ����ƺ���һ��BUG��
	// // Ϊ���������⣬����ʹ����new File(name).getName()��
	// savedFile = new File(locDir, new File(name).getName());
	// item.write(savedFile);
	// }
	// }
	// return savedFile;
	// } catch (Exception e) {
	// e.printStackTrace();
	// throw new FileUploadException(e.getMessage());
	// }
	// }

	/**
	 * upload first file in form
	 * 
	 * TODO no test
	 * 
	 * @param locDir
	 * @param tempDir
	 * @param request
	 * @param maxSize
	 *            the max size of uploaded file
	 * @param memTempSize
	 *            the max temporary size of memory
	 * @return
	 * @throws FileUploadException
	 */
	public static File uploadSingleFile(String locDir, String tempDir,
			HttpServletRequest request, int maxSize, int memTempSize)
			throws FileUploadException {
		// Create a factory for disk-based file items
		DiskFileItemFactory factory = new DiskFileItemFactory(memTempSize,
				new File(tempDir));
		try {
			// DiskFileUpload fu = new DiskFileUpload();
			ServletFileUpload fu = new ServletFileUpload(factory);
			// the maximum size of the upload file
			fu.setSizeMax(maxSize);
			// the maximum size that will be stored in memory is 512kb
			// fu.setSizeThreshold(memTempSize);
			// fu.setRepositoryPath(tempDir);
			List fileItems = fu.parseRequest(request);
			Iterator iter = fileItems.iterator();
			File savedFile = null;
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				//忽略form元素
				if (!item.isFormField()) {
					String filename = item.getName();
					long size = item.getSize();
					if ((filename == null || filename.equals("")) && size == 0)
						continue;
					// TODO test here
					filename = filename.replace('\\', '/');
					savedFile = new File(locDir, filename);
					// savedFile = new File(locDir, new
					// File(filename).getName());
					item.write(savedFile);
					return savedFile;
				}
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			throw new FileUploadException(e.getMessage());
		}
	}

	@SuppressWarnings("unchecked")
	public static List<FileItem> getRequestBodyFormItem(
			HttpServletRequest request) throws FileUploadException {
		return new ServletFileUpload().parseRequest(request);
	}

	// public static void responseFiles(File[] in, OutputStream outputStream)
	// throws IOException {
	//
	// //write each file to response
	// for (int i = 0; i < in.length; i++) {
	// FileReader reader = new FileReader(in[i]);
	// FileInputStream fileInput = new FileInputStream(in[i]);
	// BufferedOutputStream buf = new BufferedOutputStream(
	// new FileOutputStream(in[i]));
	// outputStream.write(buf);
	// buf.close();
	// }
	// }
	public static void sendFiles(File[] in, OutputStream outputStream)
			throws IOException {
		byte[] buffer = new byte[4096];
		int bufferedNumbers;

		// write each file to response
		for (int i = 0; i < in.length; i++) {
			FileInputStream inputStream = new FileInputStream(in[i]);
			while ((bufferedNumbers = inputStream.read(buffer)) != -1) {
				outputStream.write(buffer, 0, bufferedNumbers);
			}
			inputStream.close();
		}
	}

	// public static void responseFile(File in, HttpServletResponse out)
	// throws IOException {
	// // BufferedReader br = new BufferedReader(new InputStreamReader(
	// // new FileInputStream(in)));
	// // PrintWriter outWriter = out.getWriter();
	// // String data = null;
	// // while ((data = br.readLine()) != null) {
	// // //logger.info(data);
	// // outWriter.write(data);
	// // }
	// // outWriter.close();
	// // br.close();
	// //out.setCharacterEncoding("GBK");
	// FileReader fileReader = new FileReader(in);
	// PrintWriter outWriter = out.getWriter();
	// char buffer[] = new char[4096];
	// int read = 0;
	//
	// while ((read = fileReader.read(buffer)) != -1) {
	// outWriter.write(buffer, 0, read);
	// }
	//
	// outWriter.close();
	// fileReader.close();
	// }
	//
	// public static void responseCache(char[] in, HttpServletResponse out)
	// throws IOException {
	// PrintWriter output = out.getWriter();
	// output.write(in);
	// }

}